package me.algo.tree;

import java.util.LinkedList;

/**
 * @author guozheng
 * @date 2024/4/18
 */
public class T2 {
    public static void main(String[] args) {

    }

    /**
     * 129. 求根节点到叶节点数字之和
     * @param root
     * @return
     */
    static public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }
        LinkedList<SumTree> stk = new LinkedList<>();
        int sum = 0;
        stk.addLast(new SumTree(root, 0));
        while (!stk.isEmpty()) {
            int size = stk.size();
            while (size > 0) {
                size--;
                SumTree sub = stk.removeFirst();
                TreeNode node = sub.node;
                if (node.right == null && node.left == null) {
                    int total = sub.subSum * 10 + node.val;
                    sum = sum + total;
                    continue;
                }
                if (node.left != null) {
                    stk.addLast(new SumTree(node.left, sub.subSum * 10 + node.val));
                }
                if (node.right != null) {
                    stk.addLast(new SumTree(node.right, sub.subSum * 10 + node.val));
                }
            }
        }
        return sum;
    }


    static class SumTree {
        TreeNode node;
        int subSum;

        public SumTree(TreeNode node, int subSum) {
            this.node = node;
            this.subSum = subSum;
        }
    }

}
